Before diving deep, let us first give a look on what servlet is and what are its benefits?

“Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send response back to the web server.”

Pretty straight forward, now lets have a look on its benefits.

Benefits of Servlet:-

There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows:

  • Better performance: because it creates a thread for each request, not process.

  • Portability: because it uses Java language.

  • Robust: JVM manages Servlets, so we don’t need to worry about the memory leak, garbage collection, etc.

  • Secure: because it uses java language.

Alright, lets have a look on cookies:-

“An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data stored on the user’s computer by the web browser while browsing a website.”

Cookies perform essential functions in the modern web. Perhaps most importantly, authentication cookies are the most common method used by web servers to know whether the user is logged in or not, and which account they are logged in with. Without such a mechanism, the site would not know whether to send a page containing sensitive information, or require the user to authenticate themselves by logging in. The security of an authentication cookie generally depends on the security of the issuing website and the user’s web browser, and on whether the cookie data is encrypted. Security vulnerabilities may allow a cookie’s data to be read by a hacker, used to gain access to user data, or used to gain access (with the user’s credentials) to the website to which the cookie belongs (see cross-site scripting and cross-site request forgery for examples).


Setting up our project

What we need as our setup?

Nothing more, except these two :-

  • Eclipse IDE (Eclipse IDE for Enterprise Java Developers)

  • Apache Tomcat (for setting and starting up server)

Steps to create new project:-

  1. Open Eclipse IDE.

  2. Click on File -> New -> Dynamic Web Project. Following dialog box will appear.

Image

  1. We enter “login”(changeable) as our project name and select Apache Tomcat as our runtime.

  2. Leaving all other settings to default and clicking on finish, we are ready with our project setup.

Folder Structure and files to edit:-

  • For creating our project, our project needs some java files(for servlet), our webpages which will be served, and XML for servlet mapping and other informations.

  • In eclipse, we will store our java files in a package in directory “Java Resources/src” , which here is named as com.divyalogin.

  • Our web pages will be stored in a WebContent folder and web.xml in WebContent/WEB-INF folder.

  • After doing this, we will get our project directory something like this:- Image


    Done with the setup part, we will proceed to coding:-

Web Part (HTML and CSS)

1. index.html:- Homepage

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@500&amp;display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cedarville+Cursive&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./style.css" type="text/css" />
</head>
<body>
    <div class="main">
        <div class="sign-part">
            <svg class="backimg" viewBox="0 0 828 1080" fill="none" xmlns="http://www.w3.org/2000/svg">
                <ellipse cx="5.5" cy="565.5" rx="822.5" ry="954.5" fill="#673AB7" />
            </svg>
            <div class="sign-form">
                <form class="sign-form">

                    <div class="form-row">
                        <span>
                            <h1 id="topic">This is an example for implementing servlet</h1>
                        </span>

                    </div>
                    <div class="form-row">
                        <a class="signin-btn" href="login.html">Log in</a>
                    </div>
                    <div class="form-row">
                        <a class="signin-btn" href="LogoutServlet">Log Out</a>
                    </div>
                    <div class="form-row">
                        <a class="signin-btn" href="VaultServlet">Check your vault</a>
                    </div>
                </form>
            </div>
        </div>
        <div class="vault-part">
            <div class="vault-door-outer">
                <div class="vault-door-inner">
                    <div class="vault-door-lock-shadow">
                    </div>
                    <div class="vault-door-lock-wrapper">
                        <div class="vault-door-lock vault-door-circle">
                        </div>
                        <div class="vault-door-lock vault-door-pistons">
                            <div class="piston piston1">
                            </div>
                            <div class="piston piston2">
                            </div>
                            <div class="piston piston3">
                            </div>
                            <div class="piston piston4">
                            </div>
                        </div>
                    </div>
                    <div class="vault-door-handle-shadow">
                    </div>
                    <div class="vault-door-handle-long-shadow">
                    </div>
                    <div class="vault-door-handle">
                        <div class="handle-bar bar1">
                        </div>
                        <div class="handle-bar bar2">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

2.login.html:- Login Page

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@500&amp;display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cedarville+Cursive&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./style.css" type="text/css" />
</head>

<body>
    <div class="main">
        <div class="sign-part">
            <svg class="backimg" viewBox="0 0 828 1080" fill="none" xmlns="http://www.w3.org/2000/svg">
                <ellipse cx="5.5" cy="565.5" rx="822.5" ry="954.5" fill="#673AB7" />
            </svg>
            <a href="index.html" style="position: absolute;bottom:0;left:0;z-index:5" id="topic">Return to Home</a>
            <form class="sign-form" action="LoginServlet" method="post">
                <div class="form-row col">
                    <label id="topic" for="name">Enter name</label>
                    <input type="text" name="name" id="name" placeholder="Enter User Name">
                </div>
                <div class="form-row col">
                    <label id="topic" for="name">Enter password</label>
                    <input type="password" name="password" id="password" placeholder="Enter Password">
                </div>
                <div class="form-row">
                    <button class="signin-btn" type="submit">Log in</button>
                </div>
                </form>
            
        </div>
        <div class="vault-part">
            <div class="status">
                <h1>
                    Status:Locked
                </h1>
            </div>
            <div class="vault-door-outer">
                <div class="vault-door-inner">
                    <div class="vault-door-lock-shadow">
                    </div>
                    <div class="vault-door-lock-wrapper">
                        <div class="vault-door-lock vault-door-circle">
                        </div>
                        <div class="vault-door-lock vault-door-pistons">
                            <div class="piston piston1">
                            </div>
                            <div class="piston piston2">
                            </div>
                            <div class="piston piston3">
                            </div>
                            <div class="piston piston4">
                            </div>
                        </div>
                    </div>
                    <div class="vault-door-handle-shadow">
                    </div>
                    <div class="vault-door-handle-long-shadow">
                    </div>
                    <div class="vault-door-handle">
                        <div class="handle-bar bar1">
                        </div>
                        <div class="handle-bar bar2">
                        </div>
                    </div>
                </div>
            </div>
            <div class="msg">
                <h1>
                    Enter credentials to Open
                </h1>
            </div>
        </div>
    </div>

</body>

</html>

3. lock.html:-

HTML to be sent when user checks his vault and he is authenticated.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lock</title>
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@500&amp;display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cedarville+Cursive&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./style.css" type="text/css" />
</head>

<body>
    <div class="main" style="flex-direction: column;justify-content:space-around">
        <a href="index.html" style="position: absolute;bottom:0;left:0;z-index:5" id="topic">Return to Home</a>
        <div class="status">
            <h1>
                Your vault is Closed
            </h1>
        </div>
        <div class="vault-door-outer active">
            <div class="vault-door-inner">
                <div class="vault-door-lock-shadow">
                </div>
                <div class="vault-door-lock-wrapper">
                    <div class="vault-door-lock vault-door-circle">
                    </div>
                    <div class="vault-door-lock vault-door-pistons">
                        <div class="piston piston1">
                        </div>
                        <div class="piston piston2">
                        </div>
                        <div class="piston piston3">
                        </div>
                        <div class="piston piston4">
                        </div>
                    </div>
                </div>
                <div class="vault-door-handle-shadow">
                </div>
                <div class="vault-door-handle-long-shadow">
                </div>
                <div class="vault-door-handle">
                    <div class="handle-bar bar1">
                    </div>
                    <div class="handle-bar bar2">
                    </div>
                </div>
            </div>
        </div>
        <div class="msg">
            <a href="login.html">
                Open Vault
            </a>
        </div>
    </div>
    </div>
</body>
</html>

4. open.html:-

HTML to be sent when user checks his vault and he is authenticated.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Open</title>
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@500&amp;display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cedarville+Cursive&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./style.css" type="text/css" />
    <style type="text/css">
    .vault-door-outer.vault-door-outer:hover .vault-door-lock-shadow {
  width: 40%;
  margin: 44% 6.5%;
  transition: all 0.5s ease-out;
}
.vault-door-outer.vault-door-outer:hover .piston {
  width: 70%;
  margin-left: 14%;
  margin-right: 5%;
  transition: all 0.5s ease-out;
}
.vault-door-outer.vault-door-outer:hover .vault-door-handle {
  transform: rotate(-180deg);
  transition: all 1s ease-in-out;
}</style>
</head>

<body>
    <div class="main" style="flex-direction: column;justify-content:space-around">
        <a href="index.html" style="position: absolute;bottom:0;left:0;z-index:5" id="topic">Return to Home</a>
        <div class="status">
            <h1>
                Congrats:Your vault is Open
            </h1>
        </div>
        <div class="vault-door-outer active">
            <div class="vault-door-inner">
                <div class="vault-door-lock-shadow">
                </div>
                <div class="vault-door-lock-wrapper">
                    <div class="vault-door-lock vault-door-circle">
                    </div>
                    <div class="vault-door-lock vault-door-pistons">
                        <div class="piston piston1">
                        </div>
                        <div class="piston piston2">
                        </div>
                        <div class="piston piston3">
                        </div>
                        <div class="piston piston4">
                        </div>
                    </div>
                </div>
                <div class="vault-door-handle-shadow">
                </div>
                <div class="vault-door-handle-long-shadow">
                </div>
                <div class="vault-door-handle">
                    <div class="handle-bar bar1">
                    </div>
                    <div class="handle-bar bar2">
                    </div>
                </div>
            </div>
        </div>
        <div class="msg">
            <a href="LogoutServlet">
                Close Vault
            </a>
        </div>
    </div>
    </div>
</body>
</html>

5. style.css:-

Styling of HTML pages

body,
html {
  background-color: #00bcd4;
  width: 100vw;
  max-width: 99vw;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  font-family: "Quicksand", sans-serif;
}
.main {
  width: 100vw;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow:hidden;
  flex-wrap: wrap;
}

.sign-part {
  width: 40%;
  display: flex;
  height: 100vh;
}
.backimg {
  height: 100%;
  width: auto;
  position: absolute;
  z-index: 0;
}
.sign-form {
  height: 100%;
  z-index: 3;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-right: 4vw;
}
input {
  background-color: #cbefff;
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
  border-radius: 10px;
  color: #08202c;
  border-color: #b3e5fc;
  min-width: 100%;
  padding: 15px;
  margin: 30px;
}
#topic {
  font-family: "Cedarville Cursive", cursive;
  font-weight: 300;
  font-size: 2rem;
  color: #ffffff;
}
.form-row {
  margin-top: 5%;
  margin-bottom: 5%;
  display: flex;
}
.col {
  flex-direction: column;
}
.vault-part {
  width: 60%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.signin-btn {
  background: none;
  border: none;
  height: 36px;
  width: 100%;
  display: -ms-flexbox;
  display: box;
  display: flex;
  font-family: "Quicksand";
  -o-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  border-radius: 3px;
  background-color: #00bcd4;
  font-size: 18px;
  padding: 5px 20px 5px 20px;
  cursor: default;
  color: #ffffff;
  text-decoration: none;
}
.signin-btn:hover {
  background-color: #023c7e;
  transition: all 0.5s;
}
.form-row {
  display: flex;
  align-items: center;
  justify-content: center;
}

.status > h1 {
  font-size: 3.5rem;
}
.msg > a {
  color: #08202c;
  text-decoration: none;
  font-size: 2rem;
  font-weight: bold;
}

@media (max-width: 768px) {
  .sign-part,
  .vault-part {
    width: 100%;
  }
  .sign-part {
    height: 40vh;
    margin: 0;
    padding: 0%;
  }
  .sign-part > .backimg {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    writing-mode: tb-rl;
    -ms-writing-mode: bt-rl;
    height: 130vw;
    margin-top: -20vh;
  }
}
/* Vault part*/
.vault-door-outer {
  position: relative;
  width: 50vh;
  height: 50vh;
  background: #b3e5fc;
  border-radius: 6%;
  box-shadow: 0px 0px 41px #7c4dff;
}
.vault-door-outer .vault-door-inner {
  position: absolute;
  margin: 10%;
  width: 78%;
  height: 78%;
  background: #03a9f4;
  border-radius: 25%;
}
.vault-door-outer .vault-door-inner .vault-door-lock-shadow {
  position: absolute;
  width: 68%;
  height: 36%;
  background: -webkit-linear-gradient(rgba(160, 160, 160, 0.2), transparent);
  margin: 34% 18%;
  transform: rotate(-45deg);
  transition: all 0.05s ease-out;
}
.vault-door-outer .vault-door-inner .vault-door-lock {
  background: #023c7e;
}
.vault-door-outer .vault-door-inner .vault-door-circle {
  position: absolute;
  width: 80%;
  height: 80%;
  margin: 10%;
  border-radius: 50%;
}
.vault-door-outer .vault-door-inner .vault-door-pistons {
  position: absolute;
  width: 90%;
  height: 90%;
  margin: 47% 6.5%;
  background: none;
}
.vault-door-outer .vault-door-inner .vault-door-pistons .piston {
  position: absolute;
  background: #0288d1;
  width: 100%;
  height: 7%;
  border-radius: 8px;
  transition: all 0.05s ease-out;
}
.vault-door-outer .vault-door-inner .vault-door-pistons .piston.piston2 {
  transform: rotate(45deg);
}
.vault-door-outer .vault-door-inner .vault-door-pistons .piston.piston3 {
  transform: rotate(90deg);
}
.vault-door-outer .vault-door-inner .vault-door-pistons .piston.piston4 {
  transform: rotate(135deg);
}
.vault-door-outer .vault-door-inner .vault-door-handle-shadow {
  position: absolute;
  background: #00499c;
  width: 40%;
  height: 40%;
  margin: 32%;
  border-radius: 50%;
}
.vault-door-outer .vault-door-inner .vault-door-handle-long-shadow {
  position: absolute;
  background: -webkit-linear-gradient(#00499c, transparent);
  width: 45%;
  height: 45%;
  margin: 50%;
  transform: rotate(-45deg);
}
.vault-door-outer .vault-door-inner .vault-door-handle {
  position: absolute;
  border: solid 2.5vh #0288d1;
  width: 34%;
  height: 34%;
  margin: 28%;
  border-radius: 50%;
  transition: all 0.3s ease-in-out;
}
.vault-door-outer .vault-door-inner .vault-door-handle .handle-bar {
  position: absolute;
  background: #0288d1;
  height: 18%;
  width: 115%;
  margin: 40% -8%;
}
.vault-door-outer .vault-door-inner .vault-door-handle .handle-bar.bar1 {
  transform: rotate(45deg);
}
.vault-door-outer .vault-door-inner .vault-door-handle .handle-bar.bar2 {
  transform: rotate(135deg);
}
.vault-door-outer.vault-door-outer:hover .vault-door-lock-shadow {
  width: 40%;
  margin: 44% 6.5%;
  transition: all 0.5s ease-out;
}
.vault-door-outer.vault-door-outer:hover .piston {
  width: 88%;
  margin-left: 5%;
  margin-right: 5%;
  transition: all 0.5s ease-out;
}
.vault-door-outer.vault-door-outer:hover .vault-door-handle {
  transform: rotate(-180deg);
  transition: all 1s ease-in-out;
}

/* Vault Part end */

Done with HTML and CSS, now we will create our servlets:-

1. LoginServlet.java:-

This checks the login details and make user authenticated corresponding to it.

package com.divyalogin;

import java.io.IOException;
import java.io.PrintWriter;
//import all required java servlets libraries
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        
        // Extract username and password from request.
        String name=request.getParameter("name");
        String password=request.getParameter("password");
        
        if(name.equals("divyaprakash") && password.equals("rangerx")){
            // Here as our username and password matched, we will authenticate, create a cookie and return reponse.
            request.getRequestDispatcher("open.html").include(request, response);
            Cookie cookie=new Cookie("name",name);
            response.addCookie(cookie);
        }
else{
            // As user entered wrong password, we will alert the user.
            out.print("<h4>Sorry, username or password is incorrect!</h4>");
            request.getRequestDispatcher("index.html").include(request, response);
        }   
        out.close();
    }
}

2. LogoutServlet.java:-

This logouts the user given he was authenticated earlier.

package com.divyalogin;

import java.io.IOException;
import java.io.PrintWriter;

//import all required java servlets libraries
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        
        // Here for logging out, we set age of cookie to 0 and return response.
        out.print("<h4>you are successfully logged out!</h4>");

        request.getRequestDispatcher("index.html").include(request, response);
        
        Cookie cookie=new Cookie("name","");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        
    }
}

3. VaultServlet.java:-

This checks the authentication and returns corresponding html (open.html for authenticated and close.html for unauthenticated).

package com.divyalogin;

import java.io.IOException;
import java.io.PrintWriter;

//import all required java servlets libraries
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class VaultServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        
        //As open state should only be viewed when authenticated, we will check and return response by checking the values stored in cookie.
        Cookie cookie[]=request.getCookies();
        if(cookie!=null){
         String name=cookie[0].getValue();
        if(!name.equals("")||name!=null){
            request.getRequestDispatcher("open.html").include(request, response);
        }
        }else{
            request.getRequestDispatcher("lock.html").include(request, response);
        }
        out.close();
    }

}

3.web.xml

For Servlet mappings


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.divyalogin.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>VaultServlet</display-name>
    <servlet-name>VaultServlet</servlet-name>
    <servlet-class>com.divyalogin.VaultServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>VaultServlet</servlet-name>
    <url-pattern>/VaultServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>LogoutServlet</display-name>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.divyalogin.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
  </servlet-mapping>
</web-app>

Running our Project

Done with all the coding, now its time to check our code running:-

To run the project in eclipse IDE we follow these steps:-

  1. Select your project by clicked on its name directory in projects panel.

  2. Click on Run -> Run as -> Run on Server.

  3. Here, we will select Tomcat server, then click on next.

image

  1. Here, our project will already be added in configured state, we can do this, if not done so by clicking on button.

image

  1. Click on Finish.

Our project will now being served on the localhost server on defined port ( by default 8080).

Exploring our Project in web browser

  1. Open any web browser and hit to url http://localhost:8080/login.

We can see our homepage (index.html) is served.

image

  1. We can check the current status of the vault by clicking on “Check your vault” button. We can see it shows vault in locked state.

image

  1. Click on return to home and then click on “Log In” button. Here we will enter our username (divyaprakash) and password (rangerx) to open our vault, which if we enter incorrect prompts us to enter correct one.

image

image 4. After providing right credentials, we are served page in which vault is open. We can also verify the creation of cookies using developer tools. image image 5. The vault will be open for the time until we close the vault or log out, which we can verify by returning to home and again checking the current vault state. image image 6. Now, if we log out or close our vault, our vault state changes to close state until we again log in. This can also be verified as inspecting this time, there would be no cookie present. image image image 7. As our all steps are complete, we can switch off our server by navigating to Window -> Show View -> Servers. Here right click on running server and click on stop. image


In this way, we have successfully implemented login and logout with the help of cookies.